#!/usr/bin/env python
# -*- coding: UTF-8 -*-

from datetime import datetime, timedelta

class Task:
    def __init__(self, name):
        self.name = name
        self.periods = []
        self.period = None
        self.parent = None
        self.ticking = False

    def start(self):
        """
        Create a new period and start it.
        """
        if not self.ticking: 
            self.period = Period()
            self.period.start()
            self.ticking = True

    def stop(self):
        """
        Stop the ticking period and add it to the periods list
        """
        if self.ticking:
            self.period.stop()
            self.periods.append(self.period)
            self.period = None
            self.ticking = False

    def sum(self):
        """
        Returns the sum of the periods in a pair (hours, minutes)
        """
        h, m = 0, 0
        diffs = [d.diff() for d in self.periods] + [self.__currentdiff()]
        for d in diffs:
            h, m = self.__delta2tuple(d, h, m)
        return (h, m)

    def getperiod(self):
        return self.__delta2tuple(self.__currentdiff())

    def __currentdiff(self):
        """
        Returns the difference of the current period.
        """
        if self.ticking:
            return self.period.diff()
        return Period.zerodiff()

    def __delta2tuple(self, delta, ih=0, im=0):
        """
        Convert a timedelta object to (hours, minutes) pair, adding inital
        values if present.
        """
        d = delta.days
        s = delta.seconds
        (m, s) = divmod(s, 60)
        (hh, m) = divmod(m+im, 60)
        h = d*24 + hh + ih;
        return (h, m)

class Group:
    def __init__(self, name):
        self.name = name
        self.groups = {}
        self.tasks = {}

    def addTask(self, task):
        self.tasks[task.name] = task

    def addGroup(self, group):
        self.groups[group.name] = group

class Period:
    def __init__(self):
        self.t1 = None
        self.t2 = None
    def start(self):
        self.t1 = datetime.now()
    def stop(self):
        if self.t1 is not None:
            self.t2 = datetime.now()
    def diff(self):
        if self.t2 is None:
            if self.t1 is None:
                return None
            else:
                return (datetime.now() - self.t1)
        else:
            return (self.t2 - self.t1)
    @staticmethod
    def zerodiff():
        return timedelta()


if __name__ == '__main__':
    g = Group("Main")
    t = Task("Coding")
    g.addTask(t)
    t.start()
    t.stop()
    print t.sum()
  
